<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel 文件合并工具</title>
    <!-- <script src="https://update.greasyfork.org/scripts/524640/1525620/exceljs%20440.js"></script> -->
    <script src="https://cdn.bootcdn.net/ajax/libs/exceljs/4.4.0/exceljs.js"></script>
</head>
<body>
    <h1>Excel 文件合并工具</h1>
    <input type="file" id="fileInput" multiple accept=".xlsx, .xls">
    <button onclick="mergeFiles()">合并文件</button>
    <div id="output"></div>

    <script>
        async function mergeFiles() {
            const fileInput = document.getElementById('fileInput');
            const files = fileInput.files;
            if (files.length === 0) {
                alert('请选择至少两个 Excel 文件');
                return;
            }

            const workbookPromises = Array.from(files).map(file => readWorkbookFromFile(file));
            const workbooks = await Promise.all(workbookPromises);

            const mergedWorkbook = new ExcelJS.Workbook();

            // Get worksheet names from the first workbook
            const baseWorkbook = workbooks[0];
            for (const worksheet of baseWorkbook.worksheets) {
                const sheetName = worksheet.name;
                const mergedSheet = mergedWorkbook.addWorksheet(sheetName);

                // Copy headers from the first sheet
                const headerRow = worksheet.getRow(1);
                mergedSheet.addRow(headerRow.values);

                // Copy rows from all sheets with the same name
                for (const workbook of workbooks) {
                    const currentSheet = workbook.getWorksheet(sheetName);
                    if (!currentSheet || !currentSheet.lastRow) continue;

                    for (let rowNumber = 2; rowNumber <= currentSheet.lastRow.number; rowNumber++) {
                        const row = currentSheet.getRow(rowNumber);
                        mergedSheet.addRow(row.values);
                    }
                }
            }

            const buffer = await mergedWorkbook.xlsx.writeBuffer();
            const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'merged_file.xlsx';
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        }

        async function readWorkbookFromFile(file) {
            const arrayBuffer = await file.arrayBuffer();
            return new ExcelJS.Workbook().xlsx.load(arrayBuffer);
        }
    </script>
</body>
</html>



